//
//  SMADManager.m
//  OAMobile
//
//  Created by wangweichao on 2019/3/2.
//  Copyright © 2019年 李天露. All rights reserved.
//

#import "SMADManager.h"
#import "SMAdviserView.h"
#import "AFNetworking.h"
@implementation SMADManager

+(instancetype)shareManger{
    static SMADManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[SMADManager alloc] init];
    });
    return manager;
}

- (void)advertiseViewShow {
    
    //1.判断沙盒中是否存在广告图片，如果存在直接显示
    NSString *filePath = [self getFilePathWithImageName:[[NSUserDefaults standardUserDefaults] valueForKey:adImageName]];
    
    NSString *adDetails = [[NSUserDefaults standardUserDefaults] valueForKey:adUrl];
    
    BOOL isExist = [self isFileExistWithFilePath:filePath];
    if (isExist) {  //图片存在
        SMAdviserView *advertiseView = [[SMAdviserView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        advertiseView.filePath = filePath;
        advertiseView.clickUrl = adDetails;
        [advertiseView show];
    }
    //2.无论沙盒中是否存在广告图片，都需要重新调用广告接口，判断广告接口是否更新
    [self getAdvertisingImage];

}

/**
 *  判断文件是否存在
 */
- (BOOL)isFileExistWithFilePath:(NSString *)filePath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDirectory = FALSE;
    return [fileManager fileExistsAtPath:filePath isDirectory:&isDirectory];
}


/**
 *  初始化广告页面
 */
- (void)getAdvertisingImage
{
    
    // TODO 请求广告接口
    AFHTTPSessionManager *afmanager = [AFHTTPSessionManager manager];
    afmanager.requestSerializer = [AFJSONRequestSerializer serializer];
    afmanager.responseSerializer = [AFHTTPResponseSerializer serializer];
    afmanager.requestSerializer.timeoutInterval = 30.0f;
    __weak typeof(self) weakSelf = self;
    [afmanager POST:@"https://uat.healthstarknx.com/hestar-appsvr/rest/api/v1/cms/list" parameters:@{
                                                                                                @"position":@"6",
                                                                                                @"type":@"1"
                                                                                                } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                                                                                    if (responseObject) {
                                                                                                        NSDictionary *response_dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                                                                                                                                                                                                        __strong typeof(weakSelf) strongSelf = weakSelf;
                                                                                                        NSArray *list = [response_dic objectForKey:@"obj"];
                                                                                                        NSDictionary *dic = [list firstObject];
                                                                                                        NSString *sm_image_url = [NSString stringWithFormat:@"https://uat.healthstarknx.com%@",[dic objectForKey:@"imgUrl"]];
                                                                                                        NSString *sm_click_url = [dic objectForKey:@"url"];
                                                                                                        NSString *local_img_url = [[NSUserDefaults standardUserDefaults] objectForKey:adImageName];
                                                                                                        if (local_img_url==nil || ![sm_image_url containsString:local_img_url]) {
                                                                                                            // 获取图片名:43-130P5122Z60-50.jpg
                                                                                                            NSArray *stringArr = [sm_image_url componentsSeparatedByString:@"/"];
                                                                                                            NSString *imageName = stringArr.lastObject;
                                                                                                            
                                                                                                            // 拼接沙盒路径
                                                                                                            NSString *filePath = [self getFilePathWithImageName:imageName];
                                                                                                            BOOL isExist = [self isFileExistWithFilePath:filePath];
                                                                                                            if (!isExist){// 如果该图片不存在，则删除老图片，下载新图片
                                                                                                                [self downloadAdImageWithUrl:sm_image_url imageName:imageName clickUrl:sm_click_url];
                                                                                                            }
                                                                                                        }
                                                                                                        
                                                                                                        
                                                                                                    }
                                                                                                    
                                                                                                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                                                                                    
                                                                                                }];
    
    
}

/**
 *  下载新图片
 */
- (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName clickUrl:(NSString *)clickUrl{
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //下载图片
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrl]];
        UIImage *image = [UIImage imageWithData:data];
        
        //拼接保存文件的名称
        NSString *filePath = [self getFilePathWithImageName:imageName];
        
        if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {//保存成功
            NSLog(@"保存成功");
            [self deleteOldImage];
            [[NSUserDefaults standardUserDefaults] setValue:imageName forKey:adImageName];
            [[NSUserDefaults standardUserDefaults] setValue:clickUrl forKey:adUrl];//如果有广告链接，将广告链接也保存下来
            [[NSUserDefaults standardUserDefaults] synchronize];
        }else {
            NSLog(@"保存失败");
        }
    });
}
/**
 *  删除旧广告相关
 */
- (void)deleteOldImage {
    
    NSString *imageName = [[NSUserDefaults standardUserDefaults] valueForKey:adImageName];
    if (imageName) {
        NSString *filePath = [self getFilePathWithImageName:imageName];
        NSFileManager *fileManage = [NSFileManager defaultManager];
        [fileManage removeItemAtPath:filePath error:nil];
        //把广告链接也要删掉
        [[NSUserDefaults standardUserDefaults] setValue:nil forKey:adUrl];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}
/**
 *  根据图片名拼接文件路径
 */
- (NSString *)getFilePathWithImageName:(NSString *)imageName
{
    if (imageName) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:imageName];
        
        return filePath;
    }
    
    return nil;
}
@end
